package com.tongtong.stsuserapi.service.register.Impl;

import com.tongtong.stscommon.enumration.Message;
import com.tongtong.stscommon.enumration.Status;
import com.tongtong.stscommon.exception.STSPhoneNumberValidationException;
import com.tongtong.stscommon.exception.STSRegisterException;
import com.tongtong.stscommon.message.STSMessage;
import com.tongtong.stscommon.message.STSSuccessMessage;
import com.tongtong.stscommon.utils.checker.cellphoneChecker;
import com.tongtong.stsuserapi.pojo.User;
import com.tongtong.stsuserapi.service.base.UserService;
import com.tongtong.stsuserapi.service.register.CaptchaService;
import com.tongtong.stsuserapi.service.register.UserRegisterService;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserRegisterServiceImpl implements UserRegisterService {

	@Autowired
	UserService userService;

	@Autowired
	CaptchaService captchaService;

	@Autowired
	PasswordEncoder passwordEncoder;

	@Override
	public STSMessage checkPhoneNumber(String phone) {
		// 检测手机号是否为空
		if(StringUtil.isNullOrEmpty(phone)) {
			throw new STSPhoneNumberValidationException(Status.PhoneNumberIsNull,Message.PhoneNumberIsNull);
		}
		// 检测手机号格式
		if(cellphoneChecker.isInvalidFormat(phone)) {
			throw new STSPhoneNumberValidationException(Status.PhoneNumberIllegal,Message.PhoneNumberInvalid);
		}
		// 检测手机号是否存在
		if(userService.checkPhoneNumberExits(phone)) {
			throw new STSRegisterException(Status.PhoneNumberRegistered, Message.PhoneNumberRegistered);
		}

		return STSSuccessMessage.from(Status.OK,Message.OK);
	}

	@Override
	public STSMessage checkUsername(String username) {

		if(userService.checkUsernameExits(username)) {
			throw new STSRegisterException(Status.UsernameUsed, Message.UsernameUsed);
		}
		return STSSuccessMessage.from(Status.OK,Message.OK);
	}

	@Override
	public STSMessage RegisterByTelephone(String phone, String captcha, String password) {
		// 检测手机号格式
		if(cellphoneChecker.isInvalidFormat(phone)) {
			throw new STSPhoneNumberValidationException(Status.PhoneNumberIllegal,Message.PhoneNumberInvalid);
		}
		// 检测手机号是否已注册
		if(userService.checkPhoneNumberExits(phone)) {
			throw new STSRegisterException(Status.PhoneNumberRegistered,Message.PhoneNumberRegistered);
		}

		// 验证码核验 若有错误会抛出异常
		captchaService.verifyCaptcha(phone,captcha);

		// 核验通过 创建新用户
		User newUser = new User();
		newUser.setPhone(phone);
		newUser.setPassword(passwordEncoder.encode(password));
		userService.addUser(newUser);

		return STSSuccessMessage.from(Status.OK,Message.OK);
	}
}
